from django.shortcuts import render,HttpResponseRedirect
from django.http import JsonResponse
from django.forms import model_to_dict
from app.forms import file_form
from app import models


def file(request,id):
    #获取当前页面的文件夹id，没有则认为是根目录
    parent_obj = None
    folder_id = request.GET.get('folder', '')
    if folder_id.isdecimal():
        parent_obj = models.FileRepository.objects.filter(id=int(folder_id),
                                                          file_type=2, project=request.tracer.project).first()
    if request.method == 'GET':
        form = file_form.FolderModelForm(request, parent_obj)
        folder_ls = []
        if not parent_obj:
            data = models.FileRepository.objects.filter(project=request.tracer.project, parent__isnull=True).order_by('-file_type')
        else:
            data = models.FileRepository.objects.filter(project=request.tracer.project, parent=parent_obj).order_by('-file_type')
            while parent_obj:
                folder_ls.insert(0,model_to_dict(parent_obj,['id','name']))
                parent_obj = parent_obj.parent
        result = {'form':form, 'file_list':data, 'folder_ls':folder_ls}
        print('folder_ls:',folder_ls)
        print('parent_obj:',parent_obj)
        return render(request, 'app/file.html', result)
    else:
        form = file_form.FolderModelForm(request, parent_obj, data=request.POST)
        if form.is_valid():
            form.instance.project = request.tracer.project
            form.instance.file_type = 2
            form.instance.update_user = request.tracer.user
            form.instance.parent = parent_obj
            form.save()
            return JsonResponse({'status':True})
        return JsonResponse({'status':False,'errors':form.errors})